using Digitalmes.Domain.Entities.Mes.Equipments;

namespace Digitalmes.Application.Mes.Equipments.Alarms.Commands;

/// <summary>
/// 警报定义更新命令。
/// </summary>
public sealed record UpdateAlarmItemCommand(long Id, EquipAlarmItemDto AlarmItem) : IRequest<IResult<bool>>;

internal sealed class UpdateAlarmItemCommandHandler(IRepository<EquipAlarmItem> repo) : IRequestHandler<UpdateAlarmItemCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(UpdateAlarmItemCommand request, CancellationToken cancellationToken)
    {
        if (await repo.IsAnyAsync(m => m.LineCode == request.AlarmItem.LineCode
            && m.WorkCenter == request.AlarmItem.WorkCenter
            && m.Index == request.AlarmItem.Index
            && m.Id != request.Id, cancellationToken))
        {
            return Result.Failure("警报定义索引编号已存在");
        }

        var alarmItem = await repo.GetByIdAsync(request.Id, cancellationToken);
        if (alarmItem == null)
        {
            return Result.Failure("未找到要更新的警报定义");
        }

        alarmItem.Index = request.AlarmItem.Index;
        alarmItem.Content = request.AlarmItem.Content;
        alarmItem.Category = request.AlarmItem.Category;
        alarmItem.AlarmLevel = request.AlarmItem.AlarmLevel;

        var ok = await repo.UpdateAsync(alarmItem, m => new
        {
            m.Index,
            m.Content,
            m.Category,
            m.AlarmLevel,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
